package com.douguo.recipe;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.douguo.recipe.network.Constant;
import com.douguo.recipe.network.GetCalendar;
import com.douguo.recipe.network.GetPhoto;
import com.douguo.recipe.network.Util;
import com.douguo.recipe.object.Caipu;
import com.douguo.recipe.provider.DBHelper;
import com.douguo.recipe.view.NavigationView;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.TextView;

public class CalendarActivity extends DouguoActivity {

	private static final int MENU_VIEW_RECIPE = Menu.FIRST;
	private static final int MENU_DEL_RECIPE = Menu.FIRST + 1;

	// --------------dialog-------------
	private static final int DIALOG_WAIT = 0;

	// -------------msg---------------
	public static final int MSG_CALENDAR = 0;
	public static final int MSG_PHOTO = 1;
	private static final int MENU_HOME = Menu.FIRST;
	// -------------data-------------
	// private int mYear;
	// private int mMonth;
	private Calendar mCalendar;
	private List<Map<String, Object>> mList;
	// ------------------------------

	// -------------ui---------------
	private Button mBtnPrev;
	private Button mBtnCurrent;
	private Button mBtnNext;
	private GridView mGridView;
	private NavigationView mNavigation;
	private Button mBtnBack;
	// ------------------------------

	// -------------adapter-----------
	private SimpleAdapter mAdapter;

	// -------------------------------
	// --------------DBhelper----------
	private DBHelper mDBHelper;

	// --------------------------------

	private Handler mhandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_CALENDAR:
				int i = 0;
				List<com.douguo.recipe.object.Calendar> calendars = (List<com.douguo.recipe.object.Calendar>) msg.obj;
				try {
					dismissDialog(DIALOG_WAIT);
				} catch (IllegalArgumentException e) {
					// do nothing
				}
				if (calendars != null) {
					for (com.douguo.recipe.object.Calendar calendar : calendars) {
						int pos = Integer.valueOf(calendar.mDay) - 1;
						// if (Integer.valueOf(calendar.mDay).equals(i + 1)) {
						Caipu caipuTmp = new Caipu();
						caipuTmp.id = calendar.mRecipeId;
						if (mDBHelper.hasRecipe(caipuTmp)) {// 本地缓存
							Caipu caipu = mDBHelper
									.getRecipe(calendar.mRecipeId);
							if (pos < mList.size()) {
								Map<String, Object> value = mList.get(pos);
								if (value != null) {
									value.put("recipeName", caipu.name);
									value.put(
											"recipeImg",
											Util.read40X40BitmapFromSDCard(caipu.thumbPath));
									value.put("recipeId", caipu.id);
									value.put("calendarId", calendar.mId);
								}
							}
						} else {
							if (pos < mList.size()) {
								Map<String, Object> value = mList.get(pos);
								if (value != null) {
									value.put("recipeName", calendar.mName);
									// value.put(
									// "recipeImg",
									// Util.read40X40BitmapFromSDCard(calendar.mPicPath));
									if (Util.isDownloadPhotoPreferences(CalendarActivity.this)) {
										value.put("recipePicPath",
												calendar.mPicPath);
										value.put("networkImg", Boolean.TRUE);
									}
									// GetPhoto.getPhoto(pos, calendar.mPicPath,
									// mhandler);
									value.put("recipeId", calendar.mRecipeId);
									// value.put("calendarId", calendar.mId);
								}
							}
						}
						// }
						i++;
					}
				} else {
					Util.showShortToast(CalendarActivity.this,
							R.string.getCalendarError);
				}
				updateDataFromDB();
				break;
			case Constant.GET_PHOTO: {
				int pos = msg.arg1;
				SoftReference<Bitmap> refBitmap = (SoftReference<Bitmap>) msg.obj;
				HashMap<String, Object> hm = (HashMap<String, Object>) mList
						.get(pos);
				if (refBitmap != null) {
					Bitmap bitmap = refBitmap.get();
					if (bitmap != null) {
						hm.put("recipeImg", bitmap);
						hm.put("gettingImg", Boolean.FALSE);
						hm.remove("networkImg");
						mAdapter.notifyDataSetChanged();
					} else {
						hm.remove("gettingImg");
					}

				} else {
					hm.remove("gettingImg");
				}
				break;
			}
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.calendar);
		mDBHelper = new DBHelper(this);
		initData();
		initUI();
	}

	private void initData() {
		mCalendar = Calendar.getInstance();
		mCalendar.setTimeInMillis(System.currentTimeMillis());
		mList = new ArrayList<Map<String, Object>>();
		mAdapter = new CalendarAdapter(this, mList, R.layout.calendar_griditem,
				new String[] { "recipeImg", "recipeName", "dayOfMonth",
						"recipeId", "calendarId" }, new int[] {
						R.id.calendar_img, R.id.calendar_text,
						R.id.calendar_day });

		updateData();
		// }
	}

	private void initUI() {
		mBtnPrev = (Button) findViewById(R.id.btn_prevMonth);
		mBtnCurrent = (Button) findViewById(R.id.btn_currentMonth);
		mBtnNext = (Button) findViewById(R.id.btn_nextMonth);
		mGridView = (GridView) findViewById(R.id.gridview);

		mBtnPrev.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (mCalendar.get(Calendar.MONTH) < Calendar.JANUARY) {
					mCalendar.set(Calendar.MONTH, Calendar.DECEMBER);
					mCalendar.set(Calendar.YEAR,
							mCalendar.get(Calendar.YEAR) - 1);
				} else {
					mCalendar.set(Calendar.MONTH,
							mCalendar.get(Calendar.MONTH) - 1);
				}
				fillDate();
				updateData();

			}
		});
		mBtnNext.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				if (mCalendar.get(Calendar.MONTH) > Calendar.DECEMBER) {
					mCalendar.set(Calendar.MONTH, Calendar.JANUARY);
					mCalendar.set(Calendar.YEAR,
							mCalendar.get(Calendar.YEAR) + 1);
				} else {
					mCalendar.set(Calendar.MONTH,
							mCalendar.get(Calendar.MONTH) + 1);
				}
				fillDate();
				updateData();

			}
		});
		fillDate();

		mGridView.setAdapter(mAdapter);
		mGridView
				.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

					public void onCreateContextMenu(ContextMenu menu, View v,
							ContextMenuInfo menuInfo) {
						AdapterContextMenuInfo adapterInfo = (AdapterContextMenuInfo) menuInfo;
						int pos = adapterInfo.position;
						menu.clear();
						if (mList.get(pos).get("calendarId") != null) {
							menu.add(0, MENU_VIEW_RECIPE, 0,
									R.string.viewRecipe);
							menu.add(0, MENU_DEL_RECIPE, 0, R.string.delCaili);
						}
					}
				});

		mGridView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				startRecipeActivity(position);
			}
		});
		mNavigation = new NavigationView(this,NavigationView.STATE_MAGAZINE);
		mBtnBack = (Button) findViewById(R.id.imageButton_back);
		mBtnBack.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				finish();
			}
		});
	}

	private void fillDate() {
		int year = mCalendar.get(Calendar.YEAR);
		int month = mCalendar.get(Calendar.MONTH);
		mBtnPrev.setText("< " + String.valueOf(year) + "."
				+ String.valueOf(month));
		mBtnNext.setText(String.valueOf(year) + "." + String.valueOf(month + 2)
				+ " >");
		if (month == Calendar.JANUARY) {
			mBtnPrev.setText("< " + String.valueOf(year - 1) + "."
					+ String.valueOf(Calendar.DECEMBER + 1));
		} else if (month == Calendar.DECEMBER) {
			mBtnNext.setText(String.valueOf(year + 1) + "."
					+ String.valueOf(Calendar.JANUARY + 1) + " >");
		}
		mBtnCurrent.setText(String.valueOf(year) + getString(R.string.year)
				+ String.valueOf(month + 1) + getString(R.string.month));
	}

	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		switch (item.getItemId()) {
		case MENU_VIEW_RECIPE:
			startRecipeActivity(info.position);
			break;
		case MENU_DEL_RECIPE:
			String id = (String) mList.get(info.position).get("calendarId");
			if (mDBHelper.deleteCalendar(id)) {
				Util.showShortToast(this, R.string.delCailiSuccess);
				Map<String, Object> value = mList.get(info.position);
				if (value != null) {
					value.put("calendarId", null);
					value.put("recipeImg", null);
					value.put("recipeName", null);
					value.put("recipeId", null);
				}
			}
			mAdapter.notifyDataSetChanged();
			break;
		}
		return true;

	}

	private void startRecipeActivity(int pos) {
		Intent intent = new Intent(CalendarActivity.this, RecipeActivity.class);
		Bundle bundle = new Bundle();
		String recipeId = (String) mList.get(pos).get("recipeId");
		if (recipeId != null) {
			bundle.putString("recipeId", recipeId);
			bundle.putInt("pos", 0);
			// int[] ids = new int[listItem.size()];
			// int i = 0;
			// for (; i < listItem.size(); ++i) {
			// ids[i] = Integer
			// .valueOf((String) listItem.get(i).get("id"));
			// }
			bundle.putIntArray("ids", new int[] {});
			intent.putExtras(bundle);
			startActivity(intent);
		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, MENU_HOME, 0, R.string.backToHome);
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_HOME:
			Intent homeIntent = new Intent(this, HomeActivity.class);
			homeIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(homeIntent);
			break;
		}
		return true;

	}

	private void updateData() {
		fillData();
		GetPhoto.stopTasks();
		if (!Util.isUseNetworkPreferences(this)) {
			updateDataFromDB();
		} else {
			showDialog(DIALOG_WAIT);
			updateDataFromInternet();
		}

	}

	private void fillData() {
		mList.clear();

		int dayOfMonth = mCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		int i = 0;
		for (; i < dayOfMonth; i++) {
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("dayOfMonth", i + 1);
			mList.add(item);
		}
	}

	private void updateDataFromInternet() {
		GetCalendar.getCaipuList(mCalendar.get(Calendar.YEAR),
				mCalendar.get(Calendar.MONTH) + 1, mhandler);
	}

	private void updateDataFromDB() {
		int i = 0;
		List<com.douguo.recipe.object.Calendar> calendars = mDBHelper
				.getCalendars(mCalendar.get(Calendar.YEAR),
						mCalendar.get(Calendar.MONTH) + 1);
		for (com.douguo.recipe.object.Calendar calendar : calendars) {
			int pos = Integer.valueOf(calendar.mDay) - 1;
			// if (Integer.valueOf(calendar.mDay).equals(i + 1)) {
			Caipu caipu = mDBHelper.getRecipe(calendar.mRecipeId);
			if (pos < mList.size()) {
				Map<String, Object> value = mList.get(pos);
				if (value != null) {
					value.put("recipeName", caipu.name);
					value.put("recipeImg",
							Util.read40X40BitmapFromSDCard(caipu.thumbPath));
					value.put("recipeId", caipu.id);
					value.put("calendarId", calendar.mId);
					value.put("networkImg", Boolean.FALSE);
				}
			}
			// }
			i++;
		}
		mAdapter.notifyDataSetChanged();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_WAIT:
			ProgressDialog progressDialog = new ProgressDialog(
					CalendarActivity.this);
			progressDialog.setMessage(CalendarActivity.this
					.getString(R.string.recipeDownloading));
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setOnKeyListener(new OnKeyListener() {

				public boolean onKey(DialogInterface dialog, int keyCode,
						KeyEvent event) {
					if (keyCode == KeyEvent.KEYCODE_BACK) {
						try {
							dismissDialog(DIALOG_WAIT);
						} catch (IllegalArgumentException e) {
							// do nothing
						}
						finish();
						return true;
					}
					return false;
				}
			});
			return progressDialog;
		}
		return null;
	}

	private class CalendarAdapter extends SimpleAdapter {

		private Context mContext;
		private Bitmap mDefaultBitmap;

		public CalendarAdapter(Context context,
				List<? extends Map<String, ?>> data, int resource,
				String[] from, int[] to) {
			super(context, data, resource, from, to);
			mContext = context;
			mDefaultBitmap = BitmapFactory.decodeResource(
					mContext.getResources(), R.drawable.cookdefault80);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			ViewHolder holder;
			if (view == null) {
				view = LayoutInflater.from(mContext).inflate(
						R.layout.calendar_griditem, null);
				holder = new ViewHolder();
				holder.image = (ImageView) view.findViewById(R.id.calendar_img);
				holder.day = (TextView) view.findViewById(R.id.calendar_day);
				holder.recipe = (TextView) view
						.findViewById(R.id.calendar_text);
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			if (map.containsKey("networkImg")
					&& map.get("networkImg") == Boolean.TRUE
					&& (!map.containsKey("gettingImg") || map.get("gettingImg") == Boolean.FALSE)) {
				GetPhoto.getPhoto(position, (String) map.get("recipePicPath"),
						mhandler);
				map.put("gettingImg", Boolean.TRUE);
			}
			Bitmap recipeBitmap = (Bitmap) map.get("recipeImg");
			if (recipeBitmap == null) {
				recipeBitmap = mDefaultBitmap;
			}
			holder.image.setImageBitmap(recipeBitmap);
			holder.day.setText(String.valueOf(map.get("dayOfMonth")));
			holder.recipe.setText((String) map.get("recipeName"));
			return view;
		}
	}

	static class ViewHolder {
		TextView recipe;
		ImageView image;
		TextView day;

	}

}
